/*
 * @Author: 刘慧东
 * @Date: 2024-07-25 09:57:08
 * @LastEditors: 刘慧东
 * @LastEditTime: 2024-07-25 09:57:08
 */
package main

import (
	"context"
	"encoding/json"
	"log"
	"net"
	"net/http"
	"os"
	"time"

	"github.com/osamingo/jsonrpc/v2"
)

type (
	EchoHandler struct{}

	EchoParams struct {
		Name string `json:"name"`
	}
	EchoResult struct {
		Message string `json:"message"`
	}
)

func (h EchoHandler) ServeJSONRPC(c context.Context, params *json.RawMessage) (any, *jsonrpc.Error) {

	log.Printf("params: %v", params)

	// var p EchoParams
	// if err := jsonrpc.Unmarshal(params, &p); err != nil {
	// 	log.Print(err)
	// 	return nil, err
	// }

	return EchoResult{
		Message: time.Now().Format("2006-01-02 15:04:05"),
	}, nil
}

func main() {

	socketPath := "/tmp/my_rpc.sock"
	os.Remove(socketPath) // 删除之前可能存在的套接字文件
	// 监听 Unix 域套接字
	listener, err := net.Listen("unix", socketPath)
	if err != nil {
		log.Fatalln("Failed to listen on Unix socket:", err)
	}
	defer listener.Close()

	mr := jsonrpc.NewMethodRepository()

	h := EchoHandler{}

	mr.RegisterMethod("getDate", &h, EchoParams{}, EchoResult{})

	http.Handle("/rpc", mr)
	http.HandleFunc("/rpc/debug", mr.ServeDebug)

	if err := http.Serve(listener, http.DefaultServeMux); err != nil {
		log.Fatalln("Failed to serve RPC requests:", err)
	}
}
